/*
 * =====================================================================================
 *       Filename:  type_prompt.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2017.05.25 16:43
 *         Author:  fujiajun (fjj), fujiajun@renren1.com
 *        Company:  HOOLINKS
 * =====================================================================================
 */

#include "xshell.h"

void type_prompt(char* prompt){
    struct passwd* pwd;
    char hostname[MAXNAMELEN];
    char pathname[MAXPATHLEN];
    int length;

    // 获取用户信息，同时可以获得该用户home目录的路径
    pwd = getpwuid(getuid());
    // 获取当前路径
    getcwd(pathname, MAXPATHLEN);
    
    // 获取服务器名称，失败则标明unknow
    if(gethostname(hostname, MAXNAMELEN) == 0){
        sprintf(prompt, "[Xshell]%s@%s:", pwd->pw_name, hostname);
    } else {
        sprintf(prompt, "[Xshell]%s@unknown:", pwd->pw_name);
    }

    // 若当前路径包含了该用户home路径，那么使用~把home路径缩略
    length = strlen(prompt);
    if(strlen(pathname) < strlen(pwd->pw_dir) || strncmp(pathname, pwd->pw_dir, strlen(pwd->pw_dir)) != 0){
        sprintf(prompt + length, "%s", pathname);
    } else {
        sprintf(prompt + length, "~%s", pathname + strlen(pwd->pw_dir));
    }
    
    // 检测user ID判断用户权限，普通用户使用"$"，root用户使用"#"
    length = strlen(prompt);
    if(geteuid() == 0){
        sprintf(prompt + length, "#");
    } else {
        sprintf(prompt + length, "$");
    }
    
    // 添加一个空格以美观
    length = strlen(prompt);
    sprintf(prompt + length, " ");
}